package com.netnovelstore.typeHandler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.netnovelstore.pojo.Book;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class HashMapTypeHandler extends BaseTypeHandler<Map<String, Book>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Map<String, Book> stringBookMap, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(stringBookMap));
    }

    @Override
    public Map<String, Book> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String data = rs.getString(columnName);
        return StringUtils.isBlank(data) ? null : JSON.parseObject(data,new TypeReference<Map<String,Book>>(){});
    }

    @Override
    public Map<String, Book> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        return StringUtils.isBlank(data) ? null : JSON.parseObject(data,new TypeReference<Map<String,Book>>(){});
    }

    @Override
    public Map<String, Book> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String data = cs.getString(columnIndex);
        return StringUtils.isBlank(data) ? null : JSON.parseObject(data,new TypeReference<Map<String,Book>>(){});
    }

}
